package com.bigfans.paymentservice.api;

import com.bigfans.framework.Applications;
import com.bigfans.framework.CurrentUser;
import com.bigfans.framework.annotations.NeedLogin;
import com.bigfans.framework.event.ApplicationEventBus;
import com.bigfans.framework.web.BaseController;
import com.bigfans.framework.web.RestResponse;
import com.bigfans.model.event.payment.OrderPaidEvent;
import com.bigfans.model.event.payment.OrderPayFailureEvent;
import com.bigfans.paymentservice.api.clients.OrderServiceClient;
import com.bigfans.paymentservice.model.Order;
import com.bigfans.paymentservice.model.PayResult;
import com.bigfans.paymentservice.model.Payment;
import com.bigfans.paymentservice.service.OrderService;
import com.bigfans.paymentservice.service.PayMethodService;
import com.bigfans.paymentservice.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CompletableFuture;


/**
 * 
 * @Title: 
 * @Description: 支付
 * @author lichong 
 * @date 2016年3月1日 上午9:32:57 
 * @version V1.0
 */
@RestController
public class PaymentApi extends BaseController {
	
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private PayMethodService payMethodService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderServiceClient orderServiceClient;

	@Autowired
    private SimpMessagingTemplate messagingTemplate;

	@PostMapping("/pay")
	public RestResponse create(@RequestBody Payment payment) throws Exception{
		paymentService.create(payment);
		return RestResponse.ok(payment.getId());
	}

	@RequestMapping(value="/pay",method=RequestMethod.GET)
	@NeedLogin
	public RestResponse getPayment(@RequestParam(name="id") String orderId) throws Exception{
		CurrentUser cu = Applications.getCurrentUser();

		Payment payment = paymentService.getByOrder(cu.getUid() , orderId);
//		if(payment == null){
//			CompletableFuture<Order> myOrder = orderServiceClient.getOrder(orderId);
//			Order order = myOrder.get();
//			payment = new Payment();
//			paymentService.create(payment);
//		}

		Map<String , Object> data = new HashMap<>();
		data.put("payment", payment);
		return RestResponse.ok(data);
	}

	@RequestMapping(value="/getQrImage",method=RequestMethod.GET)
	@NeedLogin
	public RestResponse getQrImage(@RequestParam(name="orderId") String orderId) throws Exception{
		CompletableFuture<Order> orderFuture = orderServiceClient.getOrder(orderId);
		Order order = orderFuture.get();
		String qrImgPath = paymentService.generateF2FAlipayQrImage(order);
		return RestResponse.ok(qrImgPath);
	}
	
	/**
	 * 支付宝回调
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value="/alipayCallback")
	public void alipaycallback(HttpServletRequest request) throws Exception{
		Map<String,String> params = new HashMap<>();

        Map requestParams = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator();iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for(int i = 0 ; i <values.length;i++){

                valueStr = (i == values.length -1)?valueStr + values[i]:valueStr + values[i]+",";
            }
            params.put(name,valueStr);
        }

        String orderId = params.get("out_trade_no");
		Order order = orderService.load(orderId);
		if(order == null){
			order = orderServiceClient.getOrder(orderId).get();
		}
		Payment payment = new Payment();
		payment.setOrderId(orderId);
		payment.setBuyerId(order.getUserId());
		payment.setPayAmount(new BigDecimal(params.get("total_amount")));
        String status = params.get("trade_status");
        if("TRADE_SUCCESS".equals(status)){
			payment.setStatus(Payment.STATUS_PAY_SUCCESS);
        } else {
			payment.setStatus(Payment.STATUS_PAY_FAILURE);
		}
		paymentService.create(payment);
	}
	
	@RequestMapping(value="/checkStatus",method=RequestMethod.GET)
	@ResponseBody
	public RestResponse checkStatus(@RequestParam(name="orderId") String orderId) throws Exception {
		CurrentUser cu = Applications.getCurrentUser();
		Payment byOrder = paymentService.getByOrder(cu.getUid(), orderId);
		boolean hasPaid = false;
		if(byOrder != null && Payment.STATUS_PAY_SUCCESS.equals(byOrder.getStatus())){
			hasPaid = true;
		}
		return RestResponse.ok(hasPaid);
	}

//	@RequestMapping(value="/pay",method=RequestMethod.POST)
//	@NeedLogin
//	@ResponseBody
//	public AjaxResponse toThirdPaymentSite(@RequestParam(name="bankCode") String bankCode,@RequestParam(name="id") String id) throws Exception{
//		AjaxResponse resp = new AjaxResponse();
//		if(StringHelper.isEmpty(bankCode)){
//			resp.setStatus(ResponseStatus.FAILURE);
//			resp.setMessage("银行代码不正确");
//			return resp;
//		}
//		SessionUser su = redisService.getSessionUser(getUserToken());
//		Order order = orderService.getOrderByUser(su.getUid(), id);
//
//		String p0_Cmd = "Buy";
//		String p1_MerId = Configuration.getProp("yeepay.p1_merId");
//		String p2_Order = order.getSn();
//		String p3_Amt = order.getTotalPrice().toString();
//		// 开发模式下默认订单金额0.01
//		if(Configuration.getProp("system.mode").equals("dev")){
//			p3_Amt = "0.01";
//		}
//		String p4_Cur = "CNY";
//		String p5_Pid = "";
//		String p6_Pcat = "";
//		String p7_Pdesc = "";
//		String p8_Url = Configuration.getProp("yeepay.callbackurl");
//		String p9_SAF = "";
//		String pa_MP = "";
//		// 银行代码
//		String pd_FrpId = bankCode;
//		String pr_NeedResponse = "1";
//		String keyValue = Configuration.getProp("yeepay.Merchantkey");
//		String hmac = YeePay.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue);
//
//		StringBuilder params = new StringBuilder(Configuration.getProp("yeepay.url"));
//		params.append("?p0_Cmd=").append(p0_Cmd)
//		.append("&p1_MerId=").append(p1_MerId)
//		.append("&p2_Order=").append(p2_Order)
//		.append("&p3_Amt=").append(p3_Amt)
//		.append("&p4_Cur=").append(p4_Cur)
//		.append("&p5_Pid=").append(p5_Pid)
//		.append("&p6_Pcat=").append(p6_Pcat)
//		.append("&p7_Pdesc=").append(p7_Pdesc)
//		.append("&p8_Url=").append(p8_Url)
//		.append("&p9_SAF=").append(p9_SAF)
//		.append("&pa_MP=").append(pa_MP)
//		.append("&pd_FrpId=").append(pd_FrpId)
//		.append("&pr_NeedResponse=").append(pr_NeedResponse)
//		.append("&hmac=").append(hmac);
//		resp.setRedirectUrl(params.toString());
//		return resp;
//	}
//
//	/**
//	 * 支付成功回调
//	 * @param id
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value="/pay/yeepayCallback",method=RequestMethod.GET)
//	@NeedLogin
//	public String yeepaycallback() throws Exception{
//		String money = getRequest().getParameter("r3_Amt");
//		String r6_Order = getRequest().getParameter("r6_Order");
//
//		return "redirect:/order/"+r6_Order;
//	}

//	/**
//	 * 支付成功回调
//	 * @param orderId
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value="/pay_success",method=RequestMethod.GET)
//	@NeedLogin
//	public RestResponse success(@RequestParam(name="oid") String orderId) throws Exception{
//		CurrentUser cu = Applications.getCurrentUser();
//		applicationEventBus.publishEvent(new OrderPaidEvent(orderId));
//		return RestResponse.ok();
//	}
//
//	/**
//	 * 支付失败通知回调
//	 * @param orderId
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value="/pay_failure",method=RequestMethod.GET)
//	@NeedLogin
//	public RestResponse failure(@RequestParam(name="oid") String orderId) throws Exception{
//		CurrentUser cu = Applications.getCurrentUser();
//		applicationEventBus.publishEvent(new OrderPayFailureEvent(orderId));
//		return RestResponse.ok();
//	}
}
